<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Magazyn extends Controller_Main {
    
    public function after(){
//        $this->magazyn_model=Model::factory('magazyn');
//        $this->mocowania=$this->magazyn_model->getMocowania();
        
        $this->scripts[]='media/js/magazyn.js';
        

        parent::after();
    }

    public function before(){
        parent::before();

        $this->magazyn_model=Model::factory('magazyn');
        $this->mocowania=$this->magazyn_model->getMocowania();
    }

    public function action_index(){
        $this->template->title .= ' - Magazyn';
        $this->template->content = View::factory('magazyn/home' );
        if(Auth::hasRoles('manager')){
            $this->addTopActionMenu('Dziennik', URL::site('magazyn/diary'), null, array('style'=>'background-color: #4cbaff;'));
        }
    }

    public function action_edit_motor_type(){
          $this->template->title .= ' - Magazyn - Edytuj Typ silnika';
          $this->template->content = View::factory('magazyn/add_motor_type');
          $this->template->content->mocowania=$this->mocowania;
          $this->template->content->obudowy = Model_Acmotor::getObudowy();
          
          $this->addTopActionMenu('Lista modeli silników', URL::site('magazyn/motor_type_list'));

          $params = Request::current()->param();
          
          if($params['id']){
              $this->template->content->id = $params['id'];
          
              $data = array();
              $acmotortype = ORM::factory('acmotortype', $params['id']);
              $data = $acmotortype->as_array();
              
              $cennikData = $acmotortype->getCennik();
              $data = array_merge($data, $cennikData);
//              var_dump($cennikData);
          }
          
          if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
              $data = $this->get_motortype_data();
              
              $cennikData = array();
              foreach($_POST as $k=>$v){
                  if(strstr($k, 'cena_')!==false){
                      $cennikData[$k] = $v;
                  }
              }
//              var_dump($cennikData);

              $acmotortype->values($data);
              $acmotortype->save();
              
              $acmotortype->saveCennik($cennikData);
              
          }

          $this->template->content->data = $data;
    }

    /**
     * dodaj nowy typ silnika
     */
    public function action_add_motor_type(){
      $this->template->title .= ' - Magazyn - Dodaj Typ silnika';
      $this->template->content = View::factory('magazyn/add_motor_type');
      $this->template->content->mocowania = $this->mocowania;
      $this->template->content->obudowy = Model_Acmotor::getObudowy();

      $this->addTopActionMenu('Lista modeli silników', URL::site('magazyn/motor_type_list'));
      
      // save
      if(strtolower($_SERVER['REQUEST_METHOD']) =='post'){
          $this->template->content->status='done';

          $acmotortype=ORM::factory('acmotortype');

          $data = $this->get_motortype_data();

          foreach($data as &$v){
              $v = str_replace(',', '.', $v);
          }
          unset($v);

          $acmotortype->name = Request::current()->post('name');
          $date['insert_time'] = date('Y-m-d H:i:s');
          $acmotortype->values($data);
          $createF=$acmotortype->create();
          $this->template->content->createF=$createF;

          $this->request->redirect('magazyn/add_motor_type?status=add_success&info='.$acmotortype->name);

          if($createF){
            $this->template->content->info="Dodano pomyślnie";
          }else{
              $this->template->content->info="Błąd dodawania";
          }
      }

      if($_GET['status']=='add_success'){
          $this->template->content->info = "Dodano pomyślnie";
          if(Request::g('info')){
              $this->template->content->info .= '( '.Request::g('info').' )';
          }
      }

    }

    public function action_motor_type_list(){
          $this->template->title .= ' - Magazyn - Lista modeli silników';
          $this->template->content = View::factory('magazyn/motor_type_list');
          $this->template->content->mocowania=$this->mocowania;
          
          $this->addTopActionMenu('Dodaj nowy model', URL::site('magazyn/add_motor_type'), 'green');
          $this->addTopActionMenu('Sortuj modele', URL::site('magazyn/order_motor_types'), 'yellow');
          $this->addTopActionMenu('Modyfikuj cennik', URL::site('magazyn/cennik'), null, array('style'=>'background-color:#ffa65e;'));

          $acmotortype=ORM::factory('acmotortype');

          switch($this->request->g('status')){
              case'delete_success':
                  $this->template->content->info[]='Pomyślnie usunięto';
                  break;
              case'delete_fail':
                  $this->template->content->errors[]='Usunięcie nie powiodło się';
                  break;
          }
    }

    public function action_delete_motor_type(){
        $params=Request::current()->param();

        $acmotortype = ORM::factory('acmotortype', $params['id']);
        $r=$acmotortype->delete();

        if($r){
            $this->request->redirect('magazyn/motor_type_list?status=delete_success');
        }else{
            $this->request->redirect('magazyn/motor_type_list?status=delete_fail');
        }
    }

    public function action_add_motor(){
        $this->template->title .= ' - Magazyn - Dodaj silnik';
        $this->template->content = View::factory('magazyn/add_motor');
        
        $this->template->content->info = array();
        $this->template->content->errors = array();

        $id = $this->request->param('id');
        $this->template->content->id = $id;
        
        $this->addTopActionMenu('Lista silników', URL::site('magazyn/index'));
        if($id){
            $this->addTopActionMenu('Dodaj nowy silnik', URL::site('magazyn/add_motor'), 'green');
        }
        
        $user = Auth::getCurrent();

        $this->template->content->warehouses = Model_Magazyn::getWarehouses();
        array_unshift($this->template->content->warehouses, '-');

        $acmotortype = ORM::factory('acmotortype');
        $full_list2 = $acmotortype->getFullList();
        
        $full_list = array();
        $full_list['0']='-';
        foreach($full_list2 as $v){
            $full_list[$v['amt_id']] = "{$v['name']} ({$v['obroty']}/{$v['moc']}kW)";
        }
        
//        var_dump($full_list);
        
        $data = array();
        $data['delivery_time'] = date('Y-m-d');
        $data['id_warehouse'] = 1;
        $data['ref_no'] = Model_Acmotor::getMaxRef();
        $data['ref_no']++;
        
        if($id){        //  edycja
            $acmotor = ORM::factory('acmotor', $id);
            $data = $acmotor->as_array();

            if(!$acmotor->checkAvaible()){
                Request::current()->redirect('404');
            }
            
            if($data['delivery_time']){
                $data['delivery_time'] = date('Y-m-d', strtotime($data['delivery_time']));
            }else{
                $data['delivery_time'] = '';
            }
            
        }else{          // add
            $acmotor = ORM::factory('acmotor');
        }
        
        //  cena
        $data['cena'] = $acmotor->getCenaEuroNetto();
        $data['cena_pln'] = $data['cena'] * Model_Settings::getVal('cur_euro');

        // save
        if(strtolower($_SERVER['REQUEST_METHOD']) =='post'){
            
            $this->template->content->status='done';

            $ilosc = Request::current()->post('ilosc');
            $ref_no = Request::current()->post('ref_no');

            $data = array();
            $data['id_acmotor_type'] = Request::current()->post('id_acmotor_type');
            if(!$ref_no){
                $ref_no = null;
            }else{
                $data['ref_no'] = $ref_no;
            }
            $data['id_motor_mocowania'] = Request::current()->post('id_motor_mocowania');
            $data['cena_zakupu_netto_eur'] = Request::current()->post('cena_zakupu_netto_eur');
            $data['delivery_time'] = Request::current()->post('delivery_time');
            $data['id_warehouse'] = Request::current()->post('id_warehouse');
            $data['regal'] = Request::current()->post('regal');
            $data['sruby'] = Request::current()->post('sruby');
            
            if(!trim($data['delivery_time'])){
                $data['delivery_time']=null;
            }

            try {
                if(!$data['id_acmotor_type']){
                    throw new Exception('Nie wybrano modelu silnika', 1);
                }
                
                if($id){
                    $acmotor->values($data);
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $createF = $acmotor->save();
                    $last_id = $acmotor->id;
                }else{
                    
                    $data['insert_time'] = date('Y-m-d H:i:s');
                    
                    for($i=1; $i<=$ilosc; $i++,$ref_no++){
                        $new_acmotor = ORM::factory('acmotor');
                        if(!Request::current()->post('ref_no')){
                            $data['ref_no'] = null;
                        }else{
                            $data['ref_no'] = $ref_no;
                        }
                        $data['user_id'] = $user->id;
                        
                        $new_acmotor->values($data);
                        $createF = $new_acmotor->create();
                        $last_id = $new_acmotor->id;
                    }
                }
            }catch(Exception $e){
                $createF = false;
                $errMess = $e->getMessage();
            }
            if($createF){
                $this->request->redirect('magazyn/add_motor/?status=success&ggg='.$data['id_acmotor_type']);
            }else{
                $this->template->content->errors = 'Błąd zapisu. '.$errMess;
            }
        }

        $this->template->content->status = Request::g('status');

        if(Request::g('status') == 'success'){
            $this->template->content->info = 'Zapisano pomyślnie';
        }
        
        $this->template->content->data = $data;
        $this->template->content->mocowania = $this->mocowania;
        $this->template->content->type_list = $full_list;

    }
    
    public function action_order_motor_types(){
        $this->template->title .= ' - sortuj modele silników';
        $this->template->content = View::factory('magazyn/order_motor_types');
        $this->addTopActionMenu('Lista silników', URL::site('magazyn/motor_type_list'));
        
        $motorTypes = new Model_Acmotortype();
        $list = $motorTypes->getFullList(array(), true);
        
        
//        $motorTypes->swapOrderWith(5);
        
        foreach($list as &$v){
            $v['obroty'] = Model_Acmotor::obrotyFilter($v['name'], $v['obroty']);
        }
        unset($v);
        
        $this->template->content->list = $list;
    }
    
    public function action_diary(){
        $this->template->title .= ' - dziennik zdarzeń';
        $this->template->content = View::factory('magazyn/diary');
        $this->addTopActionMenu('Spis silników', URL::site('magazyn/index'));
        
        
        
        $dateFrom = Date::formatted_time('2011-10-27', 'Y-m-d');
        $dateTo = Date::nowStr('Y-m-d');
//        $magazyn = new Model_Magazyn();
//        $list = $magazyn->getDiary($dateFrom, $dateTo);
        
        $diary = Model::factory('diary');
        $diary->setDate($dateFrom, $dateTo);
        $diary->getSilnikiDiary();
        
        
        $this->template->content->list = $list;
        
    }
    
    public function action_motor_details(){
        $this->template->title .= ' - szczegóły silnika';
        $this->template->content = View::factory('magazyn/motor_details');
    }
    
    public function action_cennik(){
        $this->template->title .= ' - modyfikuj ceny zakupu';
        $this->template->content = View::factory('magazyn/cennik');
        $this->addTopActionMenu('Lista modeli silników', URL::site('magazyn/motor_type_list'));
    }
} 